package com.ithiema.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 *
 * @author wangxiao
 * @since 2022/11/1 16:33
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        String message = exception.getMessage();
//        重复数据问题
        if (message.contains("Duplicate entry")){
            String[] split = message.split("");
//            重复的数据
            String duplicateKey = split[2];
            return R.error(duplicateKey + "==== 数据已存在");
        }
        return R.error("未知错误");
    }
    /*
    异常处理方法
     */
        @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception) {
            log.info(exception.getMessage());
            return R.error(exception.getMessage());
        }
}
